package com.atguigu.zk;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;

public class ZKServer {

    private static ZooKeeper zooKeeper;

    //如何检测该服务器动态上下线,服务器在zk上创建临时节点
    public static void main(String[] args)  {
        //连接zk
        try {
            zooKeeper = new ZooKeeper("hadoop102:2181,hadoop103:2181,hadoop104:2181", 4000, new Watcher() {
                public void process(WatchedEvent event) {
                    //该线程不进行监视操作
                }
            });
            //2.在zk中创建临时节点
            //2.1判断父节点是否存在
            Stat exists = zooKeeper.exists("/xiyouji", false);
            if(exists==null){
                zooKeeper.create("/xiyouji","".getBytes(),
                        ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            }
            //创建临时节点
            zooKeeper.create("/xiyouji/"+args[0],args[1].getBytes(),
                    ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.EPHEMERAL);

            //服务端保持一直运行
            Thread.sleep(Long.MAX_VALUE);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            try {
        //关闭资源
                if (zooKeeper!=null) {
                    zooKeeper.close();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
